<template>
  <div>
    <div class="page">
      <h1>管理员登录</h1>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      ruleForm: {
        username: 'root',
        password: '123456'
      },
      // 表单验证规则
      rules: {
        // 用户名验证规则
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}  // 长度限制为4到15个字符的验证规则，当失去焦点时触发
        ],
        // 密码验证规则
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}  // 长度限制为4到15个字符的验证规则，当失去焦点时触发
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9081/admins/login';
          console.log('url = ' + url)
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ' + formData);
          this.axios.post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 2000) {
              this.$message({
                message: '登录成功!',
                type: 'success'
              });
              // 获取登录成功后的JWT
              let jwt = responseBody.data;
              // 打印JWT
              console.log('登录成功! JWT = '+jwt)
              // 将JWT存储到本地存储中
              localStorage.setItem('jwt',jwt);
              // 导航到系统管理页面
              this.$router.push('/');
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style>
body {
  background-color: #2c3e50;
}

.page {
  background-color: white;
  width: 660px;
  margin: 60px auto;
  padding: 20px 50px;
}
</style>